package com.cloudpivot.receivales.meta.service.impl;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.meta.domain.OAWFFile;
import com.cloudpivot.receivales.meta.domain.OAWFFileInfo;
import com.cloudpivot.receivales.meta.service.PvDocumentService;
import com.deepoove.poi.XWPFTemplate;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.Units;

import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.util.*;
import java.util.List;

@Service
@Slf4j
public class PvDocumentServiceImpl implements PvDocumentService {

    @Value("${fontinfo.path}")
    private String FONTPATH;

    @Value("${fontinfo.tmppath}")
    private String FILEPATH;

    /**
     * list map导入 docx
     * timeStr+signPic(Stream)
     */

    @Override
    public void insertToDocLastForDocx(List<Map<String, Object>> signsMap, InputStream signFile) {
        try {
            XWPFTemplate template = XWPFTemplate.compile(signFile);
            //创建段落
            XWPFParagraph paragraph = template.getXWPFDocument().createParagraph();
            XWPFRun run = paragraph.createRun();
            StringBuilder sb = new StringBuilder();
            //增加签名
            for (Map<String, Object> _map : signsMap) {
                InputStream in = (InputStream) _map.get("signPic");
                //指针查入图片
                run.addPicture(in, org.apache.poi.xwpf.usermodel.Document.PICTURE_TYPE_PNG, "", Units.toEMU(50), Units.toEMU(26));
                sb.append(_map.get("timeStr") + "\t");
                //查入tab
                run.addTab();
            }
            run.addBreak();
            //增加审批时间
            run.setText(sb.toString());
            template.writeAndClose(new FileOutputStream("/Users/kent/cloudpivot/docmode/out/123.docx"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insertToXlsLastForXlsx(List<Map<String, Object>> signsMap, InputStream signFile) {

    }

    /**
     * pdf 插入图片 首选使用
     *
     * @param entity
     * @param signFile 二进制数组
     */
    @Override
    public File insertToSignToPdf(OAWFFile entity, byte[] signFile) {
        try {
//            File file = new File("/Users/kent/cloudpivot/docmode/out/123.pdf");
//            File file = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
            File file = File.createTempFile(FILEPATH + UUID.randomUUID().toString(), ".tmp");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            BaseFont bf = BaseFont.createFont(FONTPATH, BaseFont.IDENTITY_H, false);
            PdfReader reader = new PdfReader(signFile);
//            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("/Users/kent_1/cloudpivot/docmode/out/123.pdf"));
            PdfStamper stamper = new PdfStamper(reader, fileOutputStream);

            int pages = reader.getNumberOfPages();//获取全部页数

            PdfContentByte overContent = null;
            //逐页增加水印
            for (int i = 1; i <= pages; i++) {
                overContent = stamper.getOverContent(i);
                addWatermark(overContent, bf);
                //最后一页增加签名
                if (i == pages) {
                    addSignDate(overContent, entity.getSignInfo(), bf);
                }
            }
            overContent.stroke();
            stamper.close();
            reader.close();

            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }
    }

    /**
     * pdf 插入水印
     *
     * @param entity
     * @param signFile 二进制数组
     */
    @Override
    public File insertToWatermarkToPdf(OAWFFile entity, byte[] signFile) {
        try {
            File file = File.createTempFile(FILEPATH + UUID.randomUUID().toString(), ".tmp");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            BaseFont bf = BaseFont.createFont(FONTPATH, BaseFont.IDENTITY_H, false);
            PdfReader reader = new PdfReader(signFile);
            PdfStamper stamper = new PdfStamper(reader, fileOutputStream);

            int pages = reader.getNumberOfPages();//获取全部页数

            PdfContentByte overContent = null;
            //逐页增加水印
            for (int i = 1; i <= pages; i++) {
                overContent = stamper.getOverContent(i);
                addWatermark(overContent, bf);
            }
            overContent.stroke();
            stamper.close();
            reader.close();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }
    }
    /**
     * 增加 水印
     */
    private void addWatermark(PdfContentByte overContent, BaseFont bf) {
        int watermarkSize = 35;
        int rotation = 35;    //角度
        int[] location1 = {100, 600};
        int[] location2 = {400, 600};
        int[] location3 = {100, 350};
        int[] location4 = {400, 350};
        int[] location5 = {100, 150};
        int[] location6 = {400, 150};

        String waterSign = "杰毅麦特";
        //配置水印对象
        PdfGState gs = new PdfGState();
        gs.setFillOpacity(0.3f);
        overContent.setGState(gs);

        overContent.beginText();
        overContent.setColorFill(BaseColor.LIGHT_GRAY);
        overContent.setFontAndSize(bf, watermarkSize);
        overContent.showTextAligned(Element.ALIGN_BASELINE, waterSign, location1[0],
                location1[1], rotation);
        overContent.endText();
        overContent.beginText();
        overContent.setColorFill(BaseColor.LIGHT_GRAY);
        overContent.setFontAndSize(bf, watermarkSize);
        overContent.showTextAligned(Element.ALIGN_BASELINE, waterSign, location2[0],
                location2[1], rotation);
        overContent.endText();

        overContent.beginText();
        overContent.setColorFill(BaseColor.LIGHT_GRAY);
        overContent.setFontAndSize(bf, watermarkSize);
        overContent.showTextAligned(Element.ALIGN_BASELINE, waterSign, location3[0],
                location3[1], rotation);
        overContent.endText();
        overContent.beginText();
        overContent.setColorFill(BaseColor.LIGHT_GRAY);
        overContent.setFontAndSize(bf, watermarkSize);
        overContent.showTextAligned(Element.ALIGN_BASELINE, waterSign, location4[0],
                location4[1], rotation);
        overContent.endText();

        overContent.beginText();
        overContent.setColorFill(BaseColor.LIGHT_GRAY);
        overContent.setFontAndSize(bf, watermarkSize);
        overContent.showTextAligned(Element.ALIGN_BASELINE, waterSign, location5[0],
                location5[1], rotation);
        overContent.endText();
        overContent.beginText();
        overContent.setColorFill(BaseColor.LIGHT_GRAY);
        overContent.setFontAndSize(bf, watermarkSize);
        overContent.showTextAligned(Element.ALIGN_BASELINE, waterSign, location6[0],
                location6[1], rotation);
        overContent.endText();
    }

    /**
     * 最后一页增加签名+日期
     */
    private void addSignDate(PdfContentByte overContent, List<OAWFFileInfo> entities, BaseFont bf) throws Exception {
        log.info("签名信息:{}", JSONObject.toJSONString(entities));
        if (Objects.isNull(entities)) {
            return;
        }
        //排序
        Collections.sort(entities);

        PdfGState gs = new PdfGState();
        gs.setFillOpacity(1f);
        overContent.setGState(gs);

        //需要分行(最多两行)
        int interCol=5; //列间隔
        int signrow = (entities.size() / interCol) + 1;
        //初始定位
        int x = 50;
        int y = 70*signrow;
        int count=1;
        for (OAWFFileInfo entity : entities) {

            //签名图片部分
            byte[] bytes = Base64.getMimeDecoder().decode(entity.getSignBase64());
            Image image = Image.getInstance(bytes);
            image.scaleAbsolute(50, 35);
            image.setAbsolutePosition(x, y);
            overContent.addImage(image);
            //字体定位
            overContent.beginText();
            overContent.setGState(gs);
            overContent.setFontAndSize(bf, 11);
            overContent.setTextMatrix(x, y-10);
//            overContent.showText(_map.get("timeStr").toString());
            overContent.showText(entity.getSignTime());
            overContent.endText();
            x += 75;
            count++;
            if (count == (interCol+1)) {
                //换行
                x=50;
                y=y-70;
            }
        }
    }

    /**
     * 串接 签名日期
     *
     * @return
     */
    private String subSignString(List<Map<String, Object>> signsMap) {
        if (Objects.isNull(signsMap)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (Map<String, Object> _map : signsMap) {
            sb.append(_map.get("timeStr") + "     ");
        }
        return sb.toString();
    }

    /**
     * base64 to inputStream
     *
     * @param base64
     * @return
     */
    private static InputStream base64ToInputStream(String base64) {
        ByteArrayInputStream stream = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64);
            stream = new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stream;
    }
}
